package com.sy.service;

import com.sy.dto.RedPacketDto;
import com.sy.mapper.RedDetailMapper;
import com.sy.mapper.RedRecordMapper;
import com.sy.mapper.RedRobRecordMapper;
import com.sy.model.RedDetail;
import com.sy.model.RedRecord;
import com.sy.model.RedRobRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
public class RedServiceImpl implements IRedService {

    @Autowired
    private RedRecordMapper daoMain;
    @Autowired
    private RedDetailMapper daoDetail;
    @Autowired
    private RedRobRecordMapper daoRob;
    /**
     * 异步把红包金额存入数据库
     * @param dto
     * @param redId
     * @param list
     * @throws Exception
     */
    @Async("asyncHandoutExecutor")
    @Transactional
    @Override
    public void recordRedPacket(RedPacketDto dto, String redId, List<Integer> list) throws Exception {

        RedRecord redRecord=new RedRecord();
        redRecord.setCreateTime(new Date());
        redRecord.setUserId(dto.getUserId());
        redRecord.setAmount(new BigDecimal(dto.getAmount()));
        redRecord.setRedPacket(redId);
        redRecord.setIsActive((byte)1);
        redRecord.setTotal(dto.getTotal());
        daoMain.insert(redRecord);
        //存入明细表 detail
        for(Integer money:list){
            RedDetail detail=new RedDetail();
            detail.setRecordId(redRecord.getId());
            detail.setAmount(new BigDecimal(money));
            detail.setCreateTime(new Date());
            detail.setIsActive((byte)1);
            daoDetail.insert(detail);
        }
    }

    //抢红包存入数据库
    @Async("asyncRobExecutor")
    @Transactional
    @Override
    public void recordRobRedPacket(Integer userId, String redId, BigDecimal amount) throws Exception {
        RedRobRecord redRobRecord=new RedRobRecord();
        redRobRecord.setIsActive((byte)1);
        redRobRecord.setUserId(userId);
        redRobRecord.setAmount(amount);
        redRobRecord.setRedPacket(redId);
        redRobRecord.setRobTime(new Date());
        daoRob.insert(redRobRecord);
    }
}
